// pages/login.ts
import Dialog from '@vant/weapp/dialog/dialog';
import api from '../../api/index';
import { encrypt } from '../../utils/util';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    userId: '',
    password: '',
    loading: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  /**
   * 登录
   */
  onBtnLogin() {
    const { userId, password } = this.data;
    const app = getApp();
    this.setData({
      loading: true
    });
    if (!this.data.userId || !this.data.password) {
      return Dialog.alert({
        title: '请检查账号密码',
        message: '有数据内容为空，请检查后再重新上报！',
      }).then(() => {
        this.setData({
          loading: false
        });
      })
    }
    api.login({
      userNo: userId, password: encrypt(password).toString()
    }).then((res: any) => {
      if (res.status === 200) {
        const token = res.map.token;
        app.globalData.isLogin = true;
        app.globalData.userInfo = { userId: res.data.userId, userName: res.data.name, phone: res.data.phone };
        if (token) {
          wx.setStorage({
            key: 'token',
            data: token
          });
        };
        api.getSite().then(res => {
          const sites: SiteItem[] = res.data;
          app.globalData.sites = sites;
          // 查询该用户管理的场
          const manageSites = app.globalData.sites?.filter(item => (
            item.custodianId === app.globalData.userInfo?.userId
          ))
          const managePools: string[] = [];
          manageSites.forEach((site: SiteItem) => {
            site.pools.forEach((pool: PoolItem) => {
              managePools.push(pool.poolNo);
            })
          });
          app.globalData.userInfo.manageSites = manageSites;
          app.globalData.userInfo.managePoolNos = managePools;
        })
        Dialog.alert({
          message: '登录成功',
        }).then(() => {
          this.setData({
            loading: false
          });
          wx.switchTab({
            url: '../collectHome/collectHome'
          })
        });
      } else {
        return Dialog.alert({
          title: '登录失败',
          message: res.msg,
        }).then(() => {
          this.setData({
            loading: false
          });
        })
      }
    }).catch((err: any) => {
      return Dialog.alert({
        title: '登录失败',
        message: err,
      })
    });
  }
})